package com.hhck.service.impl;

import com.hhck.entity.OutStore;
import com.hhck.entity.Page;
import com.hhck.entity.Result;
import com.hhck.mapper.OutStoreMapper;
import com.hhck.mapper.ProductMapper;
import com.hhck.service.OutStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OutStoreServiceImpl implements OutStoreService {

    @Autowired
    private OutStoreMapper outStoreMapper;

    @Autowired
    private ProductMapper productMapper;

    /**
     * 添加出库单（商品出库）
     */
    @Override
    public Result saveOutStore(OutStore outStore) {

        int num = outStoreMapper.insertOutStore(outStore);
        if (num == 1) {
            return Result.ok("添加成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "添加失败！");
    }

    /**
     * 分页查询出库单列表（条件查询）
     */
    @Override
    public Page queryOutStoreByPage(Page page, OutStore outStore) {

        // 查询出库单（条件查询）
        List<OutStore> outStoreList = outStoreMapper.selectOutStoreByPage(page, outStore);

        // 查询出库单总行数（条件查询）
        int count = outStoreMapper.selectOutStoreCount(outStore);
        // 设置总行数
        page.setTotalNum(count);
        // 设置总页数
        page.setPageCount(page.getPageCount());

        // 封装出库单数据
        page.setResultList(outStoreList);

        return page;
    }

    /**
     * 确认出库
     */
    // 开启事务
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer modifyOutStoreIsOutByoutsId(OutStore outStore) {

        // 查询商品库存量
        int invent = productMapper.selectProductInventByProductId(outStore.getProductId());

        // 判断库存是否充足
        if (invent < outStore.getOutNum()) {
            // 库存不足，返回-1
            return -1;
        }

        // 确认出库
        int num = outStoreMapper.updateOutStoreIsOutByOutsId(outStore);
        if (num == 1) {
            // 更新商品库存（减去出库量）
            num += productMapper.updateProductOutInventByProductId(outStore);
        }

        return num;
    }

}

